package top.linyuxb.lycloud.gateway.starter.utils.interceptor;

import cn.hutool.core.util.IdUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import top.linyuxb.lycloud.common.properties.LyGatewayProperties;

/**
 * Created by Intellij IDEA.
 *
 * @Author: linyuxb
 * @Date: 2024/8/16 11:26
 * @Desc:
 */
public class TLogHandlerInterceptorUtil {

    public static HandlerInterceptor buildHandlerInterceptor(LyGatewayProperties.LyGatewayTLogProperties tLogProperties) {
        return new HandlerInterceptor() {
            @Override
            public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
                String traceId = request.getHeader(tLogProperties.getTraceId());
                if (StringUtils.isBlank(traceId)) {
                    traceId = IdUtil.simpleUUID();
                }
                MDC.put(tLogProperties.getTraceId(), traceId);
                return HandlerInterceptor.super.preHandle(request, response, handler);
            }

            @Override
            public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
            }

            @Override
            public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
                MDC.remove(tLogProperties.getTraceId());
            }
        };
    }

}
